package leetcode;

import java.util.ArrayList;
import java.util.List;

public class LongestWordInDictionary {

	public static void main(String[] args) {
		LongestWordInDictionary object = new LongestWordInDictionary();
		String s = "aewfafwafjlwajflwajflwafj";
		List<String> list = new ArrayList<>();
		list.add("apple");
		list.add("ewaf");
		list.add("awefawfwaf");
		list.add("awef");
		list.add("awefe");
		list.add("ewafeffewafewf");
		
		System.out.println(object.findLongestWord(s, list));
	}
	
	public String findLongestWord(String s, List<String> d) {

		int maxLength = 0;
		int curLength = -1;
		String res = "";
		for (String string : d) {
			curLength  = isSubSequece(s, string);
			if(curLength > maxLength){
				maxLength = curLength;
				res = string;
			}else if(curLength == maxLength){
				if(res.compareTo(string) > 0){
					res = string;
				}
			}
		}
		return res;
	}
	
	//不是求的是否包含所有字符，而是求得是否是子序列
	private int isContain(String a, String b){
		if(a.length() < b.length()){
			return -1;
		}
		int[] map = new int[26];
		int length = a.length();
		for (int i = 0; i < length; i++) {
			map[a.charAt(i) - 'a']++;
		}
		int bLength = b.length();
		for (int i = 0; i < bLength; i++) {
			map[b.charAt(i) - 'a']--;
			if(map[b.charAt(i) - 'a'] < 0){
				return -1;
			}
		}
		return bLength;
	}
	
	private int isSubSequece(String a, String b){
		if(a.length() < b.length()){
			return -1;
		}
		int length = a.length();
		int bLength = b.length();
		int index = 0;
		
		for (int i = 0; i < length; i++) {
			if(a.charAt(i) == b.charAt(index)){
				index++;
			}
			if(index == bLength){
				break;
			}
		}
		if(index == bLength){
			return bLength;
		}else{
			return -1;
		}
	}
}
